import { NextResponse } from 'next/server'
import { toast } from 'sonner'

export const request = async (url: string, method: string, { arg }: any) => {
  let preCheckRes
  if (method == 'POST') {
    preCheckRes = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(arg),
    })
  } else {
    preCheckRes = await fetch(url)
  }
  const res = await preCheckRes.json()
  if (res.code == 200) return res?.data
  else {
    toast.error(res.code, {
      description: res.message,
    })
    return
  }
}

request.get = (url: string) => request(url, 'GET', {})

request.post = (url: string, payload: any) => request(url, 'POST', payload)

export const ok = (data: any) => {
  return NextResponse.json({
    code: 200,
    message: 'ok',
    data,
  })
}

export const fail = ({ code, message }: any) => {
  return NextResponse.json({
    code,
    message,
  })
}

export const unauthorized = () => fail({ code: 401, message: '未授权' })

export const forbidden = () =>
  fail({ code: 403, message: '权限不足，禁止访问' })

export const notFound = (message = '数据不存在') => fail({ code: 404, message })

export const internalServerError = () =>
  fail({ code: 500, message: '网络波动，请稍后再试' })

export const badRequest = (message = '请求参数错误') =>
  fail({ code: 400, message })

export const conflict = (message = '数据冲突') => fail({ code: 409, message })
